import React, { useState, useEffect } from 'react'
import Taro, { useLoad } from '@tarojs/taro'
import {
  View,
  Text,
  Button,
  ScrollView,
  RadioGroup,
  Radio,
  CheckboxGroup,
  Checkbox,
  Input
} from '@tarojs/components'
import './index.scss'

// type QuestionType = 'single' | 'multiple' | 'text'

// 定义题目接口
interface Question {
  id: number
  type: string
  title: string
  options?: string[]
  answer?: string | string[]
  correctAnswer: string | string[] // 正确答案
}

// 定义问卷数据接口
interface Questionnaire {
  id: number
  title: string
  description: string
  questions: Question[]
}

// 接口响应类型
interface ApiResponse<T> {
  success: boolean
  data: T
}

// 定义答题状态接口
type AnswerStatus = Record<number, 'correct' | 'incorrect'>

const ret = {
              "data": {
                "success": 1,
                "data": {
                  "id": 1,
                  "title": "NO1",
                  "description": "description1",
                  "questions": [{
                    "id": 1,
                    "type": "single",
                    "title": "name pls",
                    "options": ["A. TT", "B. JDG", "C. T1", "D. AG"],
                    "answer": [],
                    "correctAnswer": "A"
                  },
                  {
                    "id": 2,
                    "type": "single",
                    "title": "what you home",
                    "options": ["A. China", "B. Amercia", "C. Korean", "D. Thialand"],
                    "answer": [],
                    "correctAnswer": "C"
                  },
                  {
                    "id": 3,
                    "type": "single",
                    "title": "OOXX is what",
                    "options": ["A. CCC", "B. VVV", "C. BBB", "D. HHH"],
                    "answer": [],
                    "correctAnswer": "C"
                  }
                ]}
              }
            }

export default function Index () {
  useLoad(() => {
    console.log('question Page loaded.')
  })

  const [questionnaire, setQuestionnaire] = useState<Questionnaire | null>(null)
  const [loading, setLoading] = useState<boolean>(true)
  const [error, setError] = useState<string | null>(null)
  const [currentIndex, setCurrentIndex] = useState<number>(0)
  const [answers, setAnswers] = useState<Record<number, string | string[]>>({})
  const [isLastQuestion, setIsLastQuestion] = useState<boolean>(false)
  const [submitted, setSubmitted] = useState<boolean>(false) // 是否已提交
  const [answerStatus, setAnswerStatus] = useState<AnswerStatus>({}) // 答题状态

  const [showModal, setShowModal] = useState<boolean>(false)
  const [unanswered, setUnanswered] = useState<number[]>([])

  // 获取问卷数据
  const fetchQuestionnaire = async (id: number) => {
    try {
      setLoading(true)
      // const res = await Taro.request<ApiResponse<Questionnaire>>({
      //   url: `https://api.example.com/questionnaires/ ${id}?withCorrectAnswers=true`,
      //   method: 'GET'
      // })
      const res = ret;
      if (res.data.success) {
        setQuestionnaire(res.data.data)
        setIsLastQuestion(res.data.data.questions.length === 1)
      } else {
        setError('数据加载失败')
      }
    } catch (err) {
      setError('网络请求失败')
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  // 页面加载时获取数据
  useEffect(() => {
    const id = parseInt(Taro.getCurrentInstance().router?.params.questionnaireId || '1')
    fetchQuestionnaire(id)
  }, [])

  // 更新题目答案
  const updateAnswer = (questionId: number, value: string | string[]) => {
    setAnswers(prev => ({ ...prev, [questionId]: value }))
    
    // 自动跳转下一题
    if (currentIndex < (questionnaire?.questions.length || 1) - 1) {
      setTimeout(() => {
        updateIndex(currentIndex + 1)
      }, 300)
    }
  }

  // 提交问卷并验证答案
  const handleSubmit = () => {
    if (!questionnaire) return

    // 检查未回答的题目
    const unansweredIds = questionnaire.questions
      .filter((q) => q.answer === undefined || (Array.isArray(q.answer) && q.answer.length === 0))
      .map((q) => q.id)

    if (unansweredIds.length > 0) {
      // 弹窗提示未回答题目（已实现
      setUnanswered(unansweredIds)
      setShowModal(true)
    } else {
      // 本地校验答案
      const status: AnswerStatus = {}
      questionnaire.questions.forEach((q) => {
        const isCorrect =
          JSON.stringify(q.answer) === JSON.stringify(q.correctAnswer)
        status[q.id] = isCorrect ? 'correct' : 'incorrect'
      })
      setAnswerStatus(status)
      setSubmitted(true) // 标记已提交
    }
  }

  // 渲染题目结果卡片
  const renderResultCard = () => {
    if (!submitted || !questionnaire) return null

    const questions = questionnaire.questions

    return (
      <View className='result-card'>
        <Text className='card-title'>答题结果</Text>
        <View className='id-list'>
          {questions.map((q) => (
            <Text
              key={q.id}
              className={`id-item ${answerStatus[q.id]}`}
            >
              {q.id}
            </Text>
          ))}
        </View>
      </View>
    )
  }

  // 更新当前题目索引
  const updateIndex = (newIndex: number) => {
    if (newIndex < 0 || newIndex >= (questionnaire?.questions.length || 0)) return
    setCurrentIndex(newIndex)
    setIsLastQuestion(newIndex === (questionnaire?.questions.length || 1) - 1)
  }

  // 滑动事件处理
  const [touchStartX, setTouchStartX] = useState<number>(0)
  const handleTouchStart = (e: any) => {
    setTouchStartX(e.touches[0].clientX)
  }
  const handleTouchEnd = (e: any) => {
    const deltaX = e.changedTouches[0].clientX - touchStartX
    if (deltaX < -50 && currentIndex < (questionnaire?.questions.length || 1) - 1) {
      updateIndex(currentIndex + 1)
    }
    if (deltaX > 50 && currentIndex > 0) {
      updateIndex(currentIndex - 1)
    }
  }

  // 获取当前题目
  const currentQuestion = questionnaire?.questions[currentIndex]

  return (
    <View className='survey-container'>
      {/* 页面标题 */}
      <View className='header'>
        <Text className='title'>{questionnaire?.title}</Text>
      </View>

      {/* 加载状态 */}
      {loading && (
        <View className='loading'>
          <Text>加载中...</Text>
        </View>
      )}

      {/* 错误提示 */}
      {error && (
        <View className='error'>
          <Text>{error}</Text>
          <Button onClick={() => fetchQuestionnaire(questionnaire?.id || 1)}>重试</Button>
        </View>
      )}

      {/* 单题展示 */}
      {!loading && !error && currentQuestion && (
        <View 
          className='question-container'
          onTouchStart={handleTouchStart}
          onTouchEnd={handleTouchEnd}
        >
          <View className='question-item'>
            <Text className='question-title'>{currentQuestion.title}</Text>

            {/* 单选 */}
            {currentQuestion.type === 'single' && (
              <RadioGroup
                onChange={(e) => updateAnswer(currentQuestion.id, e.detail.checked)}
                
              >
                {currentQuestion.options?.map((option) => (
                  <View key={option} className='option'>
                    <Radio value={option} checked={answers[currentQuestion.id] === option} >{option}</Radio>
                  </View>
                ))}
              </RadioGroup>
            )}

            {/* 多选 */}
            {/* {currentQuestion.type === 'multiple' && (
              <CheckboxGroup
                onChange={(e) => updateAnswer(currentQuestion.id, e.detail.checked)}
                checked={answers[currentQuestion.id] as string[]}
              >
                {currentQuestion.options?.map((option) => (
                  <View key={option} className='option'>
                    <Checkbox value={option}>{option}</Checkbox>
                  </View>
                ))}
              </CheckboxGroup>
            )} */}

            {/* 填空 */}
            {/* {currentQuestion.type === 'text' && (
              <Input
                className='text-input'
                placeholder='请输入答案'
                value={answers[currentQuestion.id] as string}
                onInput={(e) => updateAnswer(currentQuestion.id, e.detail.value)}
              />
            )} */}
          </View>
        </View>
      )}

      {/* 底部操作栏 */}
      <View className='footer'>
        <Button className='exit-btn' onClick={() => Taro.navigateBack()}>
          退出
        </Button>
        
        {!isLastQuestion && !submitted && (
          <Button className='submit-btn' onClick={() => updateIndex(currentIndex + 1)}>
            下一题
          </Button>
        )}
        
        {isLastQuestion && !submitted && (
          <Button className='submit-btn' onClick={handleSubmit}>
            提交
          </Button>
        )}
      </View>
      
      {/* 题目导航弹窗 */}
      {showModal && (
        <View className='modal'>
          <View className='modal-content'>
            <Text>未回答的题目序号：{unanswered.join(', ')}</Text>
            <Button onClick={() => setShowModal(false)}>确认</Button>
          </View>
        </View>
      )}

      {/* 提交后结果卡片 */}
      {renderResultCard()}
    </View>
  )
}
